<script setup lang='ts'>
import { NAvatar, NButton, NCard, NEmpty, NForm, NFormItem, NGrid, NGridItem, NImage, NImageGroup, NInput, NInputNumber, NRadio, NRadioGroup, NSpace, useMessage, useNotification } from 'naive-ui'
import { h, onMounted, ref } from 'vue'
import { fetchImagesGenerations } from '@/api/index'
// import { useUserStore } from '@/store'
// const userStore = useUserStore()
const notification = useNotification()
const message = useMessage()
const formRef = ref<any>(null)
const loading = ref(false)
const imageUrls = ref([])
const imageUrlsHistory = ref([])
const model = ref({
  prompt: '性感御姐，高挺的鼻梁，金色深邃的狐狸眼，戴着无边框的眼镜，长长的金色头发，邪魅地笑着，上半身，紧身衣，真人写实',
  n: 1,
  size: '1024x1024',
})
const rules = {
  prompt: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入提示语',
  },
}

const handleValidateButtonClick = () => {
  formRef.value?.validate((errors: any) => {
    if (!errors) {
      loading.value = true
      fetchImagesGenerations(model.value).then((res: any) => {
        // console.log(res)
        imageUrls.value = res.data.data
        message.success('生成成功')
        setImageUrlsHistory(res.data)
      }).finally(() => {
        loading.value = false
      })
    }
    else {
      console.log(errors)
    }
  })
}

const setImageUrlsHistory = (urls: any) => {
  const data: any = JSON.parse(localStorage.getItem('imageList') as string)
  data.push(urls)
  // console.log(data)
  localStorage.setItem('imageList', JSON.stringify(data))
  getImageUrlsHistory()
}

const getImageUrlsHistory = () => {
  if (!localStorage.getItem('imageList'))
    localStorage.setItem('imageList', JSON.stringify([]))
  const data: any = JSON.parse(localStorage.getItem('imageList') as string)
  imageUrlsHistory.value = data.map((item: any) => {
    item.time = new Date(Number(`${item.created}000`)).toLocaleString()
    return item
  }).reverse()
  // console.log(imageUrlsHistory)
}
onMounted(() => {
  getImageUrlsHistory()
  notification.create({
    title: 'AI绘画已正式上线',
    description: '',
    content: 'AI绘画已正式上线，如需使用需要开通订阅或购买加量包，也可通过余额扣费，目前单次扣费0.3元。',
    meta: '2023-06-16 15:11',
    avatar: () =>
      h(NAvatar, {
        size: 'small',
        round: true,
        src: 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg',
      }),
    onClose: () => {

    },
  })
})
</script>

<template>
  <div class="ai-main">
    <div class="ai-title">
      <h1>AI绘画</h1>
    </div>

    <div class="ai-con">
      <NGrid cols="4" item-responsive responsive="screen" :x-gap="12" :y-gap="8">
        <NGridItem span="4 m:1 l:1">
          <NCard title="">
            <div class="ai-con-left">
              <NForm ref="formRef" :model="model" :rules="rules" :size="size" label-placement="top">
                <NFormItem :span="12" label="描述词条" path="prompt">
                  <NInput
                    v-model:value="model.prompt" placeholder="描绘你脑海中的画面*" type="textarea" :autosize="{
                      minRows: 3,
                      maxRows: 5,
                    }"
                  />
                </NFormItem>
                <NFormItem :span="12" label="图片尺寸" path="size">
                  <NRadioGroup v-model:value="model.size" name="radiogroup1">
                    <NSpace>
                      <NRadio value="1024x1024">
                        1024x1024
                      </NRadio>
                      <NRadio value="512x512">
                        512x512
                      </NRadio>
                      <NRadio value="256x256">
                        256x256
                      </NRadio>
                    </NSpace>
                  </NRadioGroup>
                </NFormItem>
                <NFormItem :span="12" label="生成数量" path="n">
                  <NInputNumber v-model:value="model.n" :min="1" :max="4" placeholder="最多生成四张图片" />
                </NFormItem>
              </NForm>
              <NButton type="primary" :loading="loading" @click="handleValidateButtonClick">
                {{ loading ? '正在生成中，请稍等' : '生成图片' }}
              </NButton>
            </div>
          </NCard>
        </NGridItem>
        <NGridItem span="4 m:3 l:3" style="height: 100%;">
          <NCard title="" style="height: 100%;">
            <div v-if="imageUrls.length == 0" class="ai-con-right">
              <NEmpty description="还没有生成图片哦，去试试吧" />
            </div>
            <NImageGroup>
              <NImage v-for="item in imageUrls" width="300" :src="item.url" />
            </NImageGroup>
          </NCard>
        </NGridItem>
      </NGrid>
    </div>

    <div v-if="imageUrlsHistory.length > 0" class="ai-title" style="padding-top: 0;">
      <h1>我的绘画</h1>
    </div>
    <div class="my-card">
      <NGrid cols="2 s:3 m:4 l:5 xl:6 2xl:7" responsive="screen" :x-gap="12" :y-gap="8">
        <NGridItem v-for="(item) in imageUrlsHistory" title="">
          <NCard style="max-width:300px">
            <template #cover>
              <NImageGroup>
                <NImage v-for="(image, index) in item.data" v-show="index == 0" width="300" :src="image.url">
                  <template #placeholder>
                    <div style="width:100%;height:100%">
                      图像加载中
                    </div>
                  </template>
                </NImage>
              </NImageGroup>
            </template>
            生成时间：{{ item.time }}
            <span style="font-size: 12px;color:#c77979">图像有效期为1小时</span>
          </NCard>
        </NGridItem>
      </NGrid>
    </div>
  </div>
</template>

<style lang="less" scoped>
.my-card {
  padding: 15px;
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.ai-main {
  color: #fff;
  background: #425d4f;
  min-height: 100vh;
}

.ai-con {
  margin: 20px;
  display: flex;
  gap: 20px;
}

.ai-title {
  text-align: center;
  font-weight: bold;
  padding-top: 20px;

  h1 {
    font-size: 25px;
  }
}

.ai-con-right {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
